import { View, ScrollView, Image } from '@tarojs/components';
import { useEffect, useState } from '@tarojs/taro';
import { request, windowHeight } from '../../../utils';
import { Config } from '../../../Config';
import { IheroData, IindexMode, IclassifyObject, ImyHeroData } from '../../../interface';
import HeroIndex from './HeroIndex';
import HeroType from './HeroType';
import pinyin from 'pinyin';
// import { AtActivityIndicator } from 'taro-ui';
import './Main.scss';
import ActivityIndicator from '../../../components/ActivityIndicator';
// import { BaseEventOrig } from '@tarojs/components/types/common';
// import { ScrollViewProps } from '@tarojs/components/types/ScrollView';

type Inos = string | number | string[] | number[];
declare global {
  interface Array<T> {
    classify: (fn: (i: T) => Inos) => IclassifyObject<T>;
  }
}
function classify<T>(this: T[], fn: (i: T) => Inos) {
  const res_arr: IclassifyObject<T> = {};
  this.forEach((item) => {
    let classifyKeyword = fn(item);
    if (typeof classifyKeyword !== 'object') {
      classifyKeyword = [classifyKeyword.toString()];
    }
    classifyKeyword.forEach((kw: number | string) => {
      const s = kw.toString();
      if (res_arr[s] === undefined) {
        res_arr[s] = [];
      }
      res_arr[s].push(item);
    });
  });
  return res_arr;
}
// 以上是数组扩展分类函数

Array.prototype.classify = classify;

const localHeroData = Taro.getStorageSync('heroData');

function Main() {
  const [heroData, setHeroData] = useState<ImyHeroData>(localHeroData);
  const [currentKey, setCurrentKey] = useState<string>('A');
  const [mode, setMode] = useState<IindexMode>('首字母');

  function handleModeChange() {
    setMode(mode === '首字母' ? '职业' : '首字母');
  }
  function handleClickHero(heroEName: string) {
    Taro.navigateTo({
      url: `/pages/heroDetail/heroDetail?ename=${heroEName}`,
    });
  }
  // const [scrollTop, setScrollTop] = useState<number>(0);
  async function getList() {
    let res = await request<IheroData[]>(Config.获取王者荣耀英雄列表);
    res = res.sort((first, second) => {
      return first.cname.localeCompare(second.cname);
    });

    const classifyResult = res.classify((item) => {
      const heroName = item.cname.replace('阿', '啊'); // 因为阿轲的名字的拼音首字母会被识别为e
      const pinyinResult: string[][] = pinyin(heroName, {
        style: pinyin.STYLE_FIRST_LETTER,
      });
      return pinyinResult.length > 0 && pinyinResult[0].length
        ? pinyinResult[0][0].toUpperCase()
        : '';
    });
    const classifyResult2 = res.classify((item) => item.hero_types);

    const myHeroData = {
      首字母: classifyResult,
      职业: classifyResult2,
      all: { all: res },
    };

    Taro.setStorage({
      key: 'heroData',
      data: myHeroData,
    });

    setHeroData(myHeroData);
  }
  useEffect(() => {
    getList();
  }, []);

  // function handleScroll(e: BaseEventOrig<ScrollViewProps.onScrollDetail>) {
  //   setScrollTop(e.detail.scrollTop);
  // }
  const myCurrentKey =
    heroData && !heroData[mode][currentKey] ? Object.keys(heroData[mode])[0] : currentKey;
  console.log({ currentKey, myCurrentKey });

  return (
    <View className="Main">
      <ScrollView
        // scrollTop={scrollTop}
        // onScroll={handleScroll}
        className="Main-ScrollView"
        style={{ height: `${windowHeight}px` }}
        scrollY
      >
        {heroData ? (
          heroData[mode][myCurrentKey].map((hero) => (
            <View
              className="Main-ScrollView-Hero"
              style={{
                backgroundImage: `url(${hero.hero_skin[0].img})`,
              }}
              key={hero.ename}
              onClick={handleClickHero.bind(this, hero.ename)}
            >
              <View className="Main-ScrollView-Hero-Left">
                {/* <AtBadge value={hero.new_type === 1 ? '新' : undefined}> */}
                <Image className="Main-ScrollView-Hero-Left-HeadIMG" src={hero.hero_img} />
                {/* </AtBadge> */}
              </View>
              <View className="Main-ScrollView-Hero-Right">
                <View className="Main-ScrollView-Hero-Right-Title">{hero.title}</View>
                <View className="Main-ScrollView-Hero-Right-Name">{hero.cname}</View>
                <HeroType type={mode === '职业' ? Number(myCurrentKey) : hero.hero_types[0]} />
              </View>
            </View>
          ))
        ) : (
          <ActivityIndicator></ActivityIndicator>
        )
        //
        }
      </ScrollView>
      {heroData && (
        <HeroIndex
          mode={mode}
          onModeChange={handleModeChange}
          current={myCurrentKey}
          indexes={Object.keys(heroData[mode])}
          onChange={setCurrentKey}
        />
      )}
    </View>
  );
}
export default Main;
